package handlers

import (
	"github.com/gin-gonic/gin"
	"post-master/models"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Video{
		Title:   title,
		Content: content,
	}
	err := models.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func List(c *gin.Context) {
	var list []models.Video
	models.DB.Debug().Find(&list)
	c.JSON(200, gin.H{
		"code": 200,
		"data": list,
		"msg":  "发布成功",
	})
	return
}
func PageList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var list []models.Video
	models.DB.Offset(offset).Limit(size).Debug().Find(&list)
	var total int64
	models.DB.Model(list).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  list,
		"msg":   "发布成功",
		"total": total,
	})
	return
}
func Delete(c *gin.Context) {
	id := c.PostForm("id")
	var video []models.Video
	err := models.DB.Delete("id=?", id).Debug().Find(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func Fun(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var list models.Video
	models.DB.Offset(offset).Limit(size).Debug().Find(&list)
	c.JSON(200, gin.H{
		"code": 200,
		"data": list,
		"msg":  "列表成功",
	})
	return
}
